/*
 * @Author: silence
 * @Date: 2022-05-24 14:23:50
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-15 16:17:24
 * @Description: 获取公共数据接口
 */

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:sil_utils_package/sil_utils_package.dart';
import 'package:package_info/package_info.dart';
import 'package:sil_base_widget_package/tools/SilUtilsTools.dart';
import '../../../entities/UpdateEntity.dart';
import '../../entities/CompanyEntity.dart';
import '../../entities/CountryEntity.dart';
import '../ApiUtils.dart';
import '../R.dart';

/**
 * 查询全局配置
 */
Future<R> api_common_global_config({required String configName}) async {
  Map<String, dynamic> params = Map();
  params['configName'] = configName;
  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.GetMethod, '/api/canAppconfig/getGlobalConfig',
      param: params);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 发送验证码
 */
Future<R> api_send_code({String? email, String? phone}) async {
  Map<String, dynamic> map = Map();

  String api = 'admin/send/sms'; // 默认手机号
  if (!SilUtilsTools.stringIsEmpty(email)) {
    api = 'email/send/sms';
    map['email'] = email;
  }

  if (!SilUtilsTools.stringIsEmpty(phone)) {
    map['phone'] = phone;
  }

  dynamic methodAwait =
      await ApiUtils.methodAwait(ApiUtils.GetMethod, api, param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 搜索国家
 */
Future<R> api_search_country({String? searchContext}) async {
  Map<String, dynamic> map = Map();

  if (!SilUtilsTools.stringIsEmpty(searchContext)) {
    map['searchContext'] = searchContext;
  }

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, '/api/CanCountry/search',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    List<CountryEntity> list = [];
    if (!SilTools.listIsEmpty(map)) {
      for (var item in map) {
        CountryEntity entity = CountryEntity.fromJson(item);
        list.add(entity);
      }
    }
    return list;
  });

  return r;
}

/**
 * 上传文件
 * type: 类型 [0:文件,1:base64编码]  
 * file: 文件或base64编码, base64编码仅支持图片格式  
 */
Future<R> api_upload_flie({int type = 0, required dynamic file}) async {
  Map<String, dynamic> map = Map();

  if (type == 0) {
    map['file'] = await MultipartFile.fromFile(file);
  } else {
    map['file'] = file;
  }

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, '/admin/common/upload',
      param: map, isFormData: type == 0, isUploadFile: true);

  R r = R.fromData(methodWait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 版本更新
 */
Future<R> api_app_version() async {
  PackageInfo info = await PackageInfo.fromPlatform();

  Map<String, dynamic> map = Map();

  /// 系统类型 1:android 2:ios 3:应用宝
  // String systemType = Platform.isIOS ? "2" : "1";
  // if (info.appName == '户用储能监测与管理系统') {
  //   systemType = '3';
  // }
  // String api = '/api/canAppconfig/latestVersion/$systemType';
  String api = '/api/canAppconfig/latestVersion/1';

  dynamic methodWait =
      await ApiUtils.methodAwait(ApiUtils.GetMethod, api, param: map);

  R r = R.fromData(methodWait, handlerData: (map) {
    UpdateEntity entity = UpdateEntity();
    if (!SilTools.mapIsEmpty(map)) {
      entity = UpdateEntity.fromJson(map);
    }
    return entity;
  });

  return r;
}

/// 得到上传后的图片地址
Future<List<String>> getUploadPicUrLPaths(List<String> imgPaths) async {
  List<String> urlList = [];

  if (imgPaths.isNotEmpty) {
    List<Future<R>> futures = [];
    imgPaths.forEach((element) {
      if (!SilUtilsTools.stringIsEmpty(element)) {
        // 如果是网络图片地址，不需要上传，直接使用
        if (element.contains('https://') || element.contains('http://')) {
          R r = R();
          r.data = element;
          futures.add(Future.value(r));
        } else {
          futures.add(api_upload_flie(file: element, type: 0));
        }
      }
    });

    try {
      List<R> futureList = await Future.wait(futures);

      futureList.forEach((R element) {
        urlList.add(element.data);
      });

      print(urlList);
    } catch (e) {
      return Future.error('上传图片出错了');
    }
  }

  return Future.value(urlList);
}

/**
 * 获取公司相关信息
 */
Future<R> api_company_info() async {
  Map<String, dynamic> map = Map();

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.GetMethod, 'admin/about/info',
      param: map);

  R r = R.fromData(methodWait, handlerData: (map) {
    CompanyEntity entity = CompanyEntity();
    if (!SilTools.mapIsEmpty(map)) {
      entity = CompanyEntity.fromJson(map);
    }
    return entity;
  });

  return r;
}

/**
 * 商务合作
 */
Future<R> api_company_cooperate({
  required String cooperateContent,
  required String countryId,
  required String email,
  required String name,
  String? phone,
  String? areaCode,
}) async {
  Map<String, dynamic> map = Map();
  map['cooperateContent'] = cooperateContent;
  map['country'] = countryId;
  map['email'] = email;
  map['name'] = name;

  if (!SilTools.stringIsEmpty(phone) && areaCode != null) {
    map['phone'] = '${areaCode}-${phone}';
  }

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, 'admin/cooperate/canAdminCooperate',
      param: map);

  R r = R.fromData(methodWait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * app意见反馈
 * content: 内容
 * contact_way：联系方式
 */
Future<R> api_common_feedback(
    {String? content, String? contact_way, List<String>? images}) async {
  Map<String, dynamic> params = Map();

  if (!SilTools.stringIsEmpty(content)) params['messageContent'] = content;
  if (!SilTools.stringIsEmpty(contact_way)) params['contact_way'] = contact_way;
  if (!SilTools.listIsEmpty(images)) params['images'] = images!;

  params['device'] = Platform.isAndroid ? 1 : 2; // 设备 [0:默认,1:Android,2:IOS]
  PackageInfo info = await PackageInfo.fromPlatform();
  params['versions'] = info.version;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, '/admin/message/canAdminMessage',
      param: params);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}
